<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader @add="addFn" :list="list"></TodoHeader>
    <TodoMain :list="showList" @del="delFn"></TodoMain>
    <TodoFooter
      :list="showList"
      :selected="taskes"
      @changetype="typeFn"
      @clear="clearFn"
    ></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import './styles/base.css'
import './styles/index.css'

import TodoHeader from './components/TodoHeader'
import TodoMain from './components/TodoMain'
import TodoFooter from './components/TodoFooter'

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('todulist')) || [],
      // 定义变量，all显示全部，no表示未完成，yes表示已完成
      taskes: 'all',
    }
  },
  methods: {
    // 添加事件，接收子组件传入的task参数
    addFn(task) {
      this.list.push({
        id: this.list.length ? this.list.at(-1).id + 1 : 100,
        name: task,
        isDone: false,
      })
    },
    // 删除事件
    delFn(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    // 完成与未完成的切换
    typeFn(type) {
      this.taskes = type
    },
    // 清空已完成
    clearFn() {
      // 将isDone为false的筛选出来
      this.list = this.list.filter((item) => item.isDone == false)
    },
  },
  // 计算属性
  computed: {
    showList() {
      if (this.taskes === 'all') {
        return this.list
      } else if (this.taskes === 'yes') {
        // 筛选已完成的
        return this.list.filter((item) => item.isDone)
      } else {
        // 筛选味完成的
        return this.list.filter((item) => !item.isDone)
      }
    },
  },
  // 数据缓存
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem('todulist', JSON.stringify(this.list))
      },
    },
  },
}
</script>
